<!--
  错误统计图表组件
  @description 错误码分布柱状图和错误详情表格
  @author AI Assistant
  @since 1.0.0
-->
<template>
  <div class="error-statistics">
    <!-- 错误码分布图表 -->
    <div ref="errorChartRef" class="chart-container" v-loading="chartLoading"></div>
    
    <!-- 错误详情表格 -->
    <div class="error-table mt-20px">
      <div class="table-title">{{ t('sop.statistics.errorDetails') }}</div>
      <el-table :data="errorData" v-loading="tableLoading" border size="small">
        <el-table-column :label="t('sop.statistics.errorCode')" prop="errorCode" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getErrorCodeTagType(scope.row.errorCode)">
              {{ scope.row.errorCode }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.errorMessage')" prop="errorMessage" min-width="200" />
        <el-table-column :label="t('sop.statistics.errorCount')" prop="errorCount" width="100" align="center">
          <template #default="scope">
            <el-tag type="danger">{{ formatNumber(scope.row.errorCount) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.errorRate')" prop="errorRate" width="120" align="center">
          <template #default="scope">
            <el-progress 
              :percentage="scope.row.errorRate" 
              color="#f56c6c"
              :show-text="false"
              style="width: 60px"
            />
            <span class="ml-8px">{{ scope.row.errorRate }}%</span>
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.firstOccurrence')" prop="firstOccurrence" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.firstOccurrence) }}
          </template>
        </el-table-column>
        <el-table-column :label="t('sop.statistics.lastOccurrence')" prop="lastOccurrence" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.lastOccurrence) }}
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 空状态 -->
      <el-empty 
        v-if="!tableLoading && errorData.length === 0"
        :description="t('sop.statistics.noErrorData')"
        :image-size="100"
        class="mt-20px"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { useI18n } from 'vue-i18n'
import { formatDate } from '@/utils/formatTime'
import * as echarts from 'echarts'
import type { ECharts } from 'echarts'
import { getErrorStatisticsApi } from '@/api/sop/statistics'
import type { ErrorStatisticsVO } from '@/api/sop/types'

defineOptions({ name: 'ErrorStatistics' })

const { t } = useI18n()

// Props
const props = defineProps<{
  dateRange: string[]
  loading: boolean
}>()

// Emits
const emit = defineEmits<{
  loadingChange: [loading: boolean]
}>()

// 响应式数据
const chartLoading = ref(false)
const tableLoading = ref(false)
const errorData = ref<ErrorStatisticsVO[]>([])

// 图表引用
const errorChartRef = ref<HTMLDivElement>()

// 图表实例
let errorChart: ECharts | null = null

/**
 * 获取错误统计数据
 */
const getErrorStatistics = async () => {
  if (!props.dateRange || props.dateRange.length !== 2) return
  
  chartLoading.value = true
  tableLoading.value = true
  emit('loadingChange', true)
  
  try {
    const data = await getErrorStatisticsApi({
      startTime: props.dateRange[0],
      endTime: props.dateRange[1]
    })
    
    errorData.value = data
    
    // 更新图表
    await nextTick()
    updateChart()
  } catch (error) {
    console.error('获取错误统计数据失败:', error)
  } finally {
    chartLoading.value = false
    tableLoading.value = false
    emit('loadingChange', false)
  }
}

/**
 * 初始化图表
 */
const initChart = () => {
  if (errorChartRef.value) {
    errorChart = echarts.init(errorChartRef.value)
  }
}

/**
 * 更新图表
 */
const updateChart = () => {
  if (!errorChart || errorData.value.length === 0) return
  
  const xAxisData = errorData.value.map(item => item.errorCode.toString())
  const seriesData = errorData.value.map(item => ({
    value: item.errorCount,
    itemStyle: {
      color: getErrorCodeColor(item.errorCode)
    }
  }))
  
  const option = {
    title: {
      text: t('sop.statistics.errorCodeDistribution'),
      left: 'center',
      textStyle: { fontSize: 14 }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' },
      formatter: (params: any) => {
        const data = params[0]
        const errorInfo = errorData.value[data.dataIndex]
        return `
          ${t('sop.statistics.errorCode')}: ${errorInfo.errorCode}<br/>
          ${t('sop.statistics.errorMessage')}: ${errorInfo.errorMessage}<br/>
          ${t('sop.statistics.errorCount')}: ${errorInfo.errorCount}<br/>
          ${t('sop.statistics.errorRate')}: ${errorInfo.errorRate}%
        `
      }
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      name: t('sop.statistics.errorCode'),
      axisLabel: {
        rotate: 45,
        fontSize: 12
      }
    },
    yAxis: {
      type: 'value',
      name: t('sop.statistics.errorCount')
    },
    series: [{
      name: t('sop.statistics.errorCount'),
      type: 'bar',
      data: seriesData,
      barWidth: '60%',
      label: {
        show: true,
        position: 'top',
        fontSize: 12
      }
    }],
    grid: { 
      left: '3%', 
      right: '4%', 
      bottom: '15%', 
      containLabel: true 
    }
  }
  
  errorChart.setOption(option)
}

/**
 * 调整图表大小
 */
const resizeChart = () => {
  errorChart?.resize()
}

/**
 * 格式化数字
 */
const formatNumber = (num: number) => {
  if (num >= 1000000) {
    return (num / 1000000).toFixed(1) + 'M'
  }
  if (num >= 1000) {
    return (num / 1000).toFixed(1) + 'K'
  }
  return num.toString()
}

/**
 * 获取错误码标签类型
 */
const getErrorCodeTagType = (code: number) => {
  if (code >= 400 && code < 500) return 'warning'
  if (code >= 500) return 'danger'
  return 'info'
}

/**
 * 获取错误码颜色
 */
const getErrorCodeColor = (code: number) => {
  if (code === 400) return '#e6a23c'
  if (code === 401) return '#f56c6c'
  if (code === 403) return '#f56c6c'
  if (code === 404) return '#909399'
  if (code === 429) return '#e6a23c'
  if (code >= 500) return '#f56c6c'
  return '#409eff'
}

// 监听日期范围变化
watch(() => props.dateRange, () => {
  getErrorStatistics()
}, { deep: true })

// 组件挂载
onMounted(async () => {
  await nextTick()
  initChart()
  getErrorStatistics()
  
  // 监听窗口大小变化
  window.addEventListener('resize', resizeChart)
})

// 组件卸载
onUnmounted(() => {
  errorChart?.dispose()
  window.removeEventListener('resize', resizeChart)
})
</script>

<style scoped>
.error-statistics {
  width: 100%;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.mt-20px {
  margin-top: 20px;
}

.ml-8px {
  margin-left: 8px;
}

.error-table {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 16px;
  text-align: center;
}
</style>
